package com.zym.controller.common.file;

import com.zym.config.ProProperties;
import com.zym.enums.AckCode;
import com.zym.exception.MyException;
import com.zym.vo.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
/*
非分片文件文件，适合小文件的上传
 */
@Api(tags = "文件操作")
@RestController
@RequestMapping("/file1")
public class FileUpload1 {
    private static final Logger log = LoggerFactory.getLogger(FileUpload1.class);
    @Autowired
    private ProProperties proProperties;

    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public R fileUpload(@RequestParam("file")MultipartFile file, HttpServletRequest request){
        //判断文件是否为空
        if (file.isEmpty()){
            return R.build(AckCode.FAIL,null,"文件不能为空");
        }
        String contentType = file.getContentType();

        //文件上传的路径
        String uploadFilePath =proProperties.getFilePath();
        //获取文件的原始名称
        String originalFilename = file.getOriginalFilename();
        //获取文件的后缀
        String substring = originalFilename.substring(originalFilename.indexOf("."));
        //生成新的文件名称
        String fileName =  UUID.randomUUID().toString().replaceAll("-", "")+substring;
        String y = new SimpleDateFormat("yyyy").format(new Date());
        String m = new SimpleDateFormat("MM").format(new Date());
        String d = new SimpleDateFormat("dd").format(new Date());
        String s1 = uploadFilePath + File.separator + y + File.separator + m + File.separator + d+File.separator;
        File file1=new File(s1 );
        //如果文件路径不存在就创建
        if (!file1.exists()){
                file1.mkdirs();
        }
        try {
            file.transferTo(new File(file1,fileName));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            log.error("文件没找到"+e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
        }
        StringBuffer url = request.getRequestURL();
        String contextPath = request.getServletContext().getContextPath();
        String requestURI = request.getRequestURI();
        int i = url.length() - request.getRequestURI().length();
//删除字符串指定下标的位置
        String s = url.delete(url.length() - requestURI.length(), url.length()).append(contextPath).toString();


        Map<String,Object> map=new HashMap<>();
        map.put("url",s+"/image/"+y+"/"+m+"/"+d+"/"+fileName);
        map.put("fileName", "image/"+y+"/"+m+"/"+d+"/"+fileName);
        map.put("newFileName", fileName);
        map.put("originalFilename", file.getOriginalFilename());
         log.info("文件上传成功");
        return R.okHasData(map);
    }
    @ApiOperation("多文件上传")
    @PostMapping("/uploads")
    public R fileUploads(@RequestParam("file")MultipartFile[] file, HttpServletRequest request){
        //判断文件是否为空
        if (file.length<=0){
            return R.build(AckCode.FAIL,null,"文件不能为空");
        }
        List<String> urls=new ArrayList<>();
        List<String> fileNames=new ArrayList<>();
        List<String> newFileNames=new ArrayList<>();
        List<String> originalFilenames=new ArrayList<>();
        for (int i = 0; i < file.length; i++) {


        String contentType = file[i].getContentType();

        //文件上传的路径
        String uploadFilePath =proProperties.getFilePath();
        //获取文件的原始名称
        String originalFilename = file[i].getOriginalFilename();
        //获取文件的后缀
        String substring = originalFilename.substring(originalFilename.indexOf("."));
        //生成新的文件名称
        String fileName =  UUID.randomUUID().toString().replaceAll("-", "")+substring;
        String y = new SimpleDateFormat("yyyy").format(new Date());
        String m = new SimpleDateFormat("MM").format(new Date());
        String d = new SimpleDateFormat("dd").format(new Date());
        String s1 = uploadFilePath + File.separator + y + File.separator + m + File.separator + d+File.separator;
        File file1=new File(s1 );
        //如果文件路径不存在就创建
        if (!file1.exists()){
            file1.mkdirs();
        }
        try {
            file[i].transferTo(new File(file1,fileName));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            log.error("文件没有找到"+e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
        }
        StringBuffer url = request.getRequestURL();
        String contextPath = request.getServletContext().getContextPath();
        String s = url.delete(url.length() - request.getRequestURI().length(), url.length()).append(contextPath).toString();
          urls.add(s+"/image/"+y+"/"+m+"/"+d+"/"+fileName);
          fileNames.add("image/"+y+"/"+m+"/"+d+"/"+fileName);
            newFileNames.add(fileName);
            originalFilenames.add(file[i].getOriginalFilename());
        }
        Map<String,Object> map=new HashMap<>();
        map.put("url",urls);
        map.put("fileName", fileNames);
        map.put("newFileName", newFileNames);
        map.put("originalFilename", originalFilenames);
        log.info("文件上传成功");
        return R.okHasData(map);
    }

    @ApiOperation("文件下载")
    @GetMapping("/down")
    public void fileDown(String fileName, HttpServletResponse response) throws UnsupportedEncodingException {
       //获取本地路径
        String localPath = proProperties.getFilePath();
        //image/2023/04/23/
        String downloadPath = localPath + StringUtils.substringAfter("/image/2023/04/24/"+fileName, "image/");
        response.reset();
        response.setContentType("application/octet-stream");
        response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
        try {
            FileInputStream in=new FileInputStream(downloadPath);
            ServletOutputStream outputStream = response.getOutputStream();
             IOUtils.copy(in,outputStream);
             outputStream.close();
             in.close();
            log.info("文件下载成功");
        } catch (FileNotFoundException e) {
            log.error("文件没有找到"+e.getMessage());
            throw new MyException(e.getMessage());


        } catch (IOException e) {
            e.printStackTrace();
        }


    }
//------------------------------------------
@ApiOperation("文件上传2")
@PostMapping("/upload2")
public R fileUpload2(@RequestParam("file")MultipartFile file, HttpServletRequest request)  {
    //判断文件是否为空
    if (file.isEmpty()){
        return R.build(AckCode.FAIL,null,"文件不能为空");
    }

    String contentType = file.getContentType();

    //文件上传的路径
    String uploadFilePath =proProperties.getFilePath();
    //获取文件的原始名称
    String originalFilename = file.getOriginalFilename();
    //获取文件的后缀
    String substring = originalFilename.substring(originalFilename.indexOf("."));
    //生成新的文件名称
    String fileName =  UUID.randomUUID().toString().replaceAll("-", "")+substring;
    String y = new SimpleDateFormat("yyyy").format(new Date());
    String m = new SimpleDateFormat("MM").format(new Date());
    String d = new SimpleDateFormat("dd").format(new Date());
    String s1 = uploadFilePath + File.separator + y + File.separator + m + File.separator + d+File.separator;
    System.out.println(s1);
    File file1 = new File(s1);
    if (!file1.exists()){
        file1.mkdirs();
    }

    InputStream inputStream = null;
    FileOutputStream fileOutputStream = null;
    try {
          inputStream = file.getInputStream();
          fileOutputStream = new FileOutputStream(s1+fileName);

        long l =IOUtils.copyLarge(inputStream, fileOutputStream, new byte[1024]);
        StringBuffer url = request.getRequestURL();
        String contextPath = request.getServletContext().getContextPath();
        String s = url.delete(url.length() - request.getRequestURI().length(), url.length()).append(contextPath).toString();


        Map<String,Object> map=new HashMap<>();
        map.put("url",s+"/image/"+y+"/"+m+"/"+d+"/"+fileName);
        map.put("fileName", "image/"+y+"/"+m+"/"+d+"/"+fileName);
        map.put("newFileName", fileName);
        map.put("originalFilename", file.getOriginalFilename());
        log.info("文件上传成功");
        System.out.println(l);
        return R.okHasData(map);

    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        org.apache.commons.io.IOUtils.closeQuietly(inputStream,fileOutputStream);
    }

return R.build(AckCode.FAIL);

}
}
